package validation

import (
	"time"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

type Page struct {
	Page     int `json:"page" form:"page"`           // 页码    (可选, 默认1)
	PageSize int `json:"page_size" form:"page_size"` // 每页数据 (可选, 默认1)
}

type StartEndTime struct {
	Start int `json:"start" form:"start"` // 起始时间
	End   int `json:"end" form:"end"`     // 截止时间
}

var GitType = []string{"gitee", "github", "gitea", "git", "gitlab"}

func init() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("ScmType", ScmType)
		v.RegisterValidation("GitScmType", GitScmType)
		v.RegisterValidation("Hour", Hour)
		v.RegisterValidation("Minute", Minute)
		v.RegisterValidation("bool", IsBool)
	}
}

var IsBool validator.Func = func(fl validator.FieldLevel) bool {
	isBool := fl.Field().String()
	if isBool == "true" || isBool == "false" {
		return true
	}
	return false
}

// 验证SCM Type
var ScmType validator.Func = func(fl validator.FieldLevel) bool {
	scm := fl.Field().String()
	collect := GitType
	collect = append(collect, "svn")
	for _, typ := range collect {
		if scm == typ {
			return true
		}
	}
	return false
}

// 验证SCM Type
var GitScmType validator.Func = func(fl validator.FieldLevel) bool {
	scm := fl.Field().String()
	for _, typ := range GitType {
		if scm == typ {
			return true
		}
	}
	return false
}

// 验证小时
var Hour validator.Func = func(fl validator.FieldLevel) bool {
	h := fl.Field().Int()
	if h >= 0 && h <= 24 {
		return true
	}
	return false
}

// 验证分钟
var Minute validator.Func = func(fl validator.FieldLevel) bool {
	min := fl.Field().Int()
	if min >= 0 && min <= 60 {
		return true
	}
	return false
}

// 校验 page 参数
func CheckPage(p *Page) {
	if p.Page <= 0 {
		p.Page = 1
	}
	if p.PageSize <= 0 {
		p.PageSize = 1
	}
}

// 校验 时间区间
func CheckStartEndTime(timeBetween *StartEndTime) {
	now := time.Now().Unix()
	if timeBetween.Start < 0 {
		timeBetween.Start = 0
	}
	if timeBetween.End <= 0 {
		timeBetween.End = int(now)
	}
	if timeBetween.Start > timeBetween.End {
		timeBetween.Start, timeBetween.End = timeBetween.End, timeBetween.Start
	}
}
